// models/user.js

// 用户角色枚举
const UserRole = {
  GUEST: 0,    // 游客
  USER: 1,     // 普通用户
  ADMIN: 2     // 管理员
};

// 用户权限枚举
const Permissions = {
  VIEW_TODO: 'view_todo',           // 查看待办
  CREATE_TODO: 'create_todo',       // 创建待办
  EDIT_TODO: 'edit_todo',           // 编辑待办
  DELETE_TODO: 'delete_todo',       // 删除待办
  MANAGE_USERS: 'manage_users',     // 管理用户
  ASSIGN_ROLES: 'assign_roles'      // 分配角色
};

// 角色权限映射
const RolePermissions = {
  [UserRole.GUEST]: [
    Permissions.VIEW_TODO
  ],
  [UserRole.USER]: [
    Permissions.VIEW_TODO,
    Permissions.CREATE_TODO,
    Permissions.EDIT_TODO
  ],
  [UserRole.ADMIN]: [
    Permissions.VIEW_TODO,
    Permissions.CREATE_TODO,
    Permissions.EDIT_TODO,
    Permissions.DELETE_TODO,
    Permissions.MANAGE_USERS,
    Permissions.ASSIGN_ROLES
  ]
};

// 用户管理类
class UserManager {
  constructor() {
    this.users = wx.getStorageSync('users') || [];
  }

  // 保存用户数据到存储
  saveUsers() {
    wx.setStorageSync('users', this.users);
  }

  // 创建新用户
  createUser(userInfo) {
    const user = {
      id: Date.now().toString(),
      ...userInfo,
      role: UserRole.USER,
      createTime: new Date().toISOString()
    };
    this.users.push(user);
    this.saveUsers();
    return user;
  }

  // 更新用户信息
  updateUser(userId, updates) {
    const index = this.users.findIndex(u => u.id === userId);
    if (index !== -1) {
      this.users[index] = { ...this.users[index], ...updates };
      this.saveUsers();
      return this.users[index];
    }
    return null;
  }

  // 删除用户
  deleteUser(userId) {
    const index = this.users.findIndex(u => u.id === userId);
    if (index !== -1) {
      this.users.splice(index, 1);
      this.saveUsers();
      return true;
    }
    return false;
  }

  // 获取用户列表
  getUsers() {
    return this.users;
  }

  // 根据ID获取用户
  getUserById(userId) {
    return this.users.find(u => u.id === userId);
  }

  // 检查用户权限
  checkPermission(userId, permission) {
    const user = this.getUserById(userId);
    if (!user) return false;
    return RolePermissions[user.role]?.includes(permission) || false;
  }

  // 设置用户角色
  setUserRole(userId, role) {
    return this.updateUser(userId, { role });
  }
}

module.exports = {
  UserRole,
  Permissions,
  RolePermissions,
  UserManager
};